﻿using System;
using System.Collections.Generic;
using PersonaLibrary.Data;
using PersonaLibrary.ViewModel.SearchPanelViewModel;

namespace PersonaLibrary.ViewModel.SearchViewModel
{
	internal class SearchViewModel<TEntity> : BaseCollectionViewModel<TEntity>
        where TEntity : class, IDBEntity
	{
		private readonly SearchPanelViewModel<TEntity> _searchPanel;
		private string _query;

		public SearchViewModel()
		{
			_searchPanel = new SearchPanelViewModel<TEntity>();
			_searchPanel.QueryCreated += SearchPanelQueryCreated;
		}

		void SearchPanelQueryCreated(string obj)
		{
			_query = obj;
			CollectionLoad();
		}

		public SearchPanelViewModel<TEntity> SearchPanel
		{
			get { return _searchPanel; }
		}

		protected override void CollectionLoad()
		{
			ObservableCollection.Clear();

			if(String.IsNullOrEmpty(_query))
				return;

			IEnumerable<TEntity> executeResult;
			try
			{
				if(typeof(TEntity) == typeof(PersonaliiReference.Employee))
					executeResult = Context.CreateAndExecuteQuery<TEntity>(string.Format("GetEmployeesByCommand?sqlCommand='{0}'", _query.Replace("'", "''")));
				else if (typeof(TEntity) == typeof(PersonaliiReference.Organization))
					executeResult = Context.CreateAndExecuteQuery<TEntity>(string.Format("GetOrganizationsByCommand?sqlCommand='{0}'", _query.Replace("'", "''")));
				else
					executeResult = new List<TEntity>();
			}
			catch (Exception e)
			{
				executeResult = new TEntity[0];
				CurrentApplication.Logger.Fault(new Exception(string.Format("Выполнение query - {0}, вызвало ошибку", _query), e));
				CurrentApplication.ShowMessage("Ошибка при поиске, пожалуйста обратитесь к разработчику");
			}
			
			foreach (TEntity singleResult in executeResult)
				ObservableCollection.Add(singleResult);

			RisePropertyChanged("Collection");
			RisePropertyChanged("CurrentPack");
		}
	}
}
